package com.onefinger.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.onefinger.domain.Constant;
import com.onefinger.domain.CustomerTable;
import com.onefinger.domain.Item;
import com.onefinger.domain.Request;
import com.onefinger.dto.NewRequest;
import com.onefinger.dto.Ticket;


@Transactional
public class RequestController implements IRequestController {

	
	@Autowired
	IRequestService requestService;
	
	@Autowired
	ICustomerTableService customerTableService;
	
	@Autowired
	IItemService itemService;
	
	@Transactional
	public Ticket newRequest(NewRequest newRequest) {
		Ticket ticket = new Ticket();
		// controlar sessionId
		CustomerTable customerTable = customerTableService.getCustomerTableByDevice( newRequest.getMac() );
		if( customerTable.getSessionId().compareTo( newRequest.getSessionId() ) != 0 )
		{
			ticket.setErrorId(Constant.NEWREQUEST_INVALIDSESSION);
		} else {
		
			if( newRequest.getItems().length != newRequest.getCounts().length )
			{
				ticket.setErrorId(Constant.NEWREQUEST_INVALIDITEMSCOUNTS);
			} else {
			
				Long[] items = newRequest.getItems();
				Long[] counts = newRequest.getCounts();
				List<Request> requests = new ArrayList<Request>();
				for (int idxItem = 0; idxItem < items.length; idxItem++) {
					Request request = new Request();
					request.setSessionId(newRequest.getSessionId());
					
					Item item = itemService.findById( items[idxItem] );
					if( item == null )
					{
						ticket.setErrorId(Constant.NEWREQUEST_INVALIDITEM);
						break;
					}
					request.setItem( item );
					request.setCount( counts[ idxItem ] );
					request.setItemPrice( item.getPrice() );
					request.setRequestMoment( new Date() );
					// 5 min de cancelacion 
					// TODO: Configurar
					request.setCancelationMoment( new Date( request.getRequestMoment().getTime() + 5L * 60 * 1000L ) );
					requests.add(request);
				}
				// no error
				if( ticket.getErrorId() == null )
				{
					for (Request request : requests) {
						requestService.save(request);
					}
				}

			}
		}
		
		List<Request> requestsInSession = requestService.listBySessionId( newRequest.getSessionId() );
		ticket.setRequests(requestsInSession);
		
		return ticket;
	}


}
